package com.csy.user.entity.system.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import javax.annotation.Resource;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.csy.commons.constant.UserConstants;
import com.csy.commons.core.exception.CustomException;
import com.csy.commons.core.utils.SecurityUtils;
import com.csy.commons.dto.SysUser;
import com.csy.commons.dto.SysUserRole;
import com.csy.commons.framework.mapper.SysUserRoleMapper;
import com.csy.user.entity.system.domain.SysUserPost;
import com.csy.user.entity.system.mapper.SysUserMapper;
import com.csy.user.entity.system.mapper.SysUserPostMapper;
import com.csy.user.entity.system.service.SysUserService;

import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;

/**
 * @Auther: sunxx
 * @Date: 2024/1/13 - 01 - 13 - 12:31
 * @Description: com.sxx.ajcommunity.system.service.impl
 * @version: 1.0
 */
@Transactional
@Service
@Slf4j
public class SysUserServiceImpl implements SysUserService {

	@Resource
	private SysUserMapper sysUserMapper;

	@Resource
	private SysUserPostMapper sysUserPostMapper;

	@Resource
	private SysUserRoleMapper sysUserRoleMapper;

	/**
	 * 根据条件分页查询用户列表
	 *
	 * @param user 用户信息
	 * @return 用户信息集合信息
	 */
	@Override
	public List<SysUser> selectUserList(SysUser user) {
		return sysUserMapper.selectUserList(user);
	}

	/**
	 * 通过用户名查询用户
	 *
	 * @param userName 用户名
	 * @return 用户对象信息
	 */
	@Override
	public SysUser selectUserByUserName(String userName) {
		return sysUserMapper.selectUserByUserName(userName);
	}

	/**
	 * 通过用户ID查询用户
	 *
	 * @param userId 用户ID
	 * @return 用户对象信息
	 */
	@Override
	public SysUser selectUserById(Long userId) {
		return sysUserMapper.selectUserById(userId);
	}

	/**
	 * 校验用户名称是否唯一
	 *
	 * @param userName 用户名称
	 * @return 结果
	 */
	@Override
	public String checkUserNameUnique(String userName) {
		int count = sysUserMapper.checkUserNameUnique(userName);
		if (count > 0) {
			return UserConstants.NOT_UNIQUE;
		}
		return UserConstants.UNIQUE;
	}

	/**
	 * 校验手机号是否唯一
	 *
	 * @param user 用户信息
	 * @return
	 */
	@Override
	public String checkPhoneUnique(SysUser user) {
		Long userId = Objects.isNull(user.getUserId()) ? -1L : user.getUserId();
		SysUser info = sysUserMapper.checkPhoneUnique(user.getPhonenumber());
		if (!Objects.isNull(info) && info.getUserId().longValue() != userId.longValue()) {
			return UserConstants.NOT_UNIQUE;
		}
		return UserConstants.UNIQUE;
	}

	/**
	 * 校验email是否唯一
	 *
	 * @param user 用户信息
	 * @return
	 */
	@Override
	public String checkEmailUnique(SysUser user) {
		Long userId = Objects.isNull(user.getUserId()) ? -1L : user.getUserId();
		SysUser info = sysUserMapper.checkEmailUnique(user.getEmail());
		if (!Objects.isNull(info) && info.getUserId().longValue() != userId.longValue()) {
			return UserConstants.NOT_UNIQUE;
		}
		return UserConstants.UNIQUE;
	}

	/**
	 * 校验用户是否允许操作
	 *
	 * @param user 用户信息
	 */
	@Override
	public void checkUserAllowed(SysUser user) {

		if (!Objects.isNull(user.getUserId()) && user.isAdmin()) {
			throw new CustomException(500, "不允许操作超级管理员用户");
		}
	}

	/**
	 * 修改用户状态
	 *
	 * @param user 用户信息
	 * @return 结果
	 */
	@Override
	@GlobalTransactional
	public int updateUserStatus(SysUser user) {
		return sysUserMapper.updateUser(user);
	}

	/**
	 * 修改用户基本信息
	 *
	 * @param user 用户信息
	 * @return 结果
	 */
	@Override
	@GlobalTransactional
	public int updateUserProfile(SysUser user) {

		return sysUserMapper.updateUser(user);
	}

	/**
	 * 修改用户头像
	 *
	 * @param userName 用户名
	 * @param avatar   头像地址
	 * @return 结果
	 */
	@Override
	@GlobalTransactional
	public boolean updateUserAvatar(String userName, String avatar) {
		return sysUserMapper.updateUserAvatar(userName, avatar) > 0;
	}

	/**
	 * 重置用户密码
	 *
	 * @param user 用户信息
	 * @return 结果
	 */
	@Override
	@GlobalTransactional
	public int resetPwd(SysUser user) {
		return sysUserMapper.updateUser(user);
	}

	/**
	 * 重置用户密码
	 *
	 * @param userName 用户名
	 * @param password 密码
	 * @return 结果
	 */
	@Override
	@GlobalTransactional
	public int resetUserPwd(String userName, String password) {
		return sysUserMapper.resetUserPwd(userName, password);
	}

	/**
	 * 查询用户所属角色组
	 *
	 * @param userName 用户名
	 * @return 结果
	 */
	@Override
	public String selectUserRoleGroup(String userName) {

		return null;
	}

	/**
	 * 查询用户所属岗位组
	 *
	 * @param userName 用户名
	 * @return 结果
	 */
	@Override
	public String selectUserPostGroup(String userName) {
		return null;
	}

	/**
	 * 新增保存用户信息
	 *
	 * @param user 用户信息
	 * @return 结果
	 */
	@Override
	@GlobalTransactional
	public int insertUser(SysUser user) {

		// 新增用户
		int row = sysUserMapper.insertUser(user);

		// 新增用户与岗位关联
		insertUserPost(user);

		// 新增用户与角色关联
		insertUserRole(user);

		return row;
	}

	/*
	 * 新增用户与角色关联
	 */
	private void insertUserRole(SysUser user) {
		Long[] roleIds = user.getRoleIds();
		if (!Objects.isNull(roleIds)) {
			List<SysUserRole> list = new ArrayList<>();
			for (Long roleId : roleIds) {
				SysUserRole sysUserRole = new SysUserRole();
				sysUserRole.setRoleId(roleId);
				sysUserRole.setUserId(user.getUserId());
				list.add(sysUserRole);
			}

			if (list.size() > 0) {
				// 查询之前用户角色关联信息，并去除
				LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
				queryWrapper.eq(SysUserRole::getUserId, user.getUserId());
				sysUserRoleMapper.delete(queryWrapper);
				
				list.forEach(sysUserRole -> {
					// 增加新的用户和角色关联信息
					sysUserRoleMapper.insert(sysUserRole);
				});
			}
		}

	}

	/*
	 * 新增用户岗位信息
	 */
	private void insertUserPost(SysUser user) {

		Long[] postIds = user.getPostIds();
		if (!Objects.isNull(postIds)) {
			List<SysUserPost> list = new ArrayList<>();
			for (Long postId : postIds) {
				SysUserPost sysUserPost = new SysUserPost();
				sysUserPost.setUserId(user.getUserId());
				sysUserPost.setPostId(postId);

				list.add(sysUserPost);
			}
			if (list.size() > 0) {
				sysUserPostMapper.batchUserPost(list);
			}
		}

	}

	/**
	 * 修改保存用户信息
	 *
	 * @param user 用户信息
	 * @return 结果
	 */
	@Override
	@GlobalTransactional
	public int updateUser(SysUser user) {
		Long userId = user.getUserId();

		// 删除用户与角色关联
		LambdaQueryWrapper<SysUserRole> lqw = new LambdaQueryWrapper<>();
		lqw.eq(SysUserRole::getUserId, userId);
		sysUserRoleMapper.delete(lqw);
		insertUserRole(user);

		// 删除用户与岗位关联
		sysUserPostMapper.deleteUserPostByUserId(userId);
		insertUserPost(user);

		return sysUserMapper.updateUser(user);
	}

	/**
	 * 通过用户ID删除用户
	 *
	 * @param userId 用户ID
	 * @return 结果
	 */
	@Override
	@GlobalTransactional
	public int deleteUserById(Long userId) {
		return sysUserMapper.deleteById(userId);
	}

	/**
	 * 批量删除用户信息
	 *
	 * @param userIds 需要删除的用户ID
	 * @return 结果
	 */
	@Override
	@GlobalTransactional
	public int deleteUserByIds(Long[] userIds) {
		return sysUserMapper.deleteUserByIds(userIds);
	}

	/**
	 * 用户修改密码
	 * 
	 * @param username
	 * @param oldPassword
	 * @param newPassword
	 * @return
	 */
	@Override
	@GlobalTransactional
	public String updatePwd(String username, String oldPassword, String newPassword) {
		BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
		// 根据用户名查出密码
		String tbPwd = sysUserMapper.selectUserByUserName(username).getPassword();
		// 查出的密码和输入的旧密码不匹配
		if (!bCryptPasswordEncoder.matches(oldPassword, tbPwd)) {
			return "401";
		}
		// 匹配
		String password = SecurityUtils.encryptPassword(newPassword);
		sysUserMapper.resetUserPwd(username, password);
		return "修改成功！";
	}

	@Override
	public SysUser getByName(String nickName) {
		return sysUserMapper.getByName(nickName);
	}

	@Override
	public SysUser getByUsername(String username) {
		return sysUserMapper.getByUsername(username);
	}

}